<template>
  <el-dialog :model-value="visible" :title="title" width="500" :close-on-click-modal="false" :show-close="false">
    <el-form ref="formRef" :model="form" :rules="formRules" label-width="auto">
      <el-form-item label="用户姓名" prop="realName">
        <el-input v-model="form.realName"></el-input>
      </el-form-item>
      <el-form-item label="登录名" prop="userName">
        <el-input v-model="form.userName"></el-input>
      </el-form-item>
      <el-form-item v-if="!props.guid" label="密码" prop="password">
        <el-input v-model="form.password"></el-input>
      </el-form-item>
      <el-form-item v-if="!props.guid" label="再次输入" prop="checkPassword">
        <el-input v-model="form.checkPassword"></el-input>
      </el-form-item>
      <el-form-item label="用户角色" prop="role">
        <el-select v-model="form.role">
          <el-option v-for="role in roleList" :key="role.code" :label="role.name" :value="role.code"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="onSubmit">提交</el-button>
        <el-button @click="emits('close', false)">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import ApiTree from '@/server/api-tree';
import { type RoleVO } from '@/server/role/types';
import type { UserVO } from '@/server/user/types';
import { type FormRules, type FormInstance, ElMessage } from 'element-plus';
import { reactive, ref, watch } from 'vue';

const emits = defineEmits(["close"])
const props = withDefaults(defineProps<{ guid: string, visible: boolean }>(), {
  guid: "",
  visible: false
})
/** 表单定义 */
const title = ref<string>(props.guid ? "编辑用户信息" : "添加用户");
const form = ref<UserVO & { checkPassword: string }>({
  guid: "",
  realName: "",
  userName: "",
  password: "",
  checkPassword: "",
  role: "",
  roleName: ""
});
const formRef = ref<FormInstance>();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const passwordValidator = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error("密码不能为空"))
  }
  if (typeof value === 'string' && (value.length < 6 || value.length > 20)) {
    return callback(new Error("密码长度必须在6-20位之间,且必须包含字母和数字"))
  }
  if (!(/[a-zA-Z]/.test(value) && /[0-9]/.test(value))) {
    return callback(new Error("密码长度必须在6-20位之间,且必须包含字母和数字"))
  }
  callback();
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const checkPasswordValidator = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error("二次密码不能为空"))
  }
  if (value !== form.value.password) {
    return callback(new Error("两次密码不一致"))
  }
  callback();
}
const formRules = reactive<FormRules<UserVO & { checkPassword: string }>>({
  realName: [{ required: true, message: "姓名不能为空" }],
  userName: [{ required: true, message: "登录名不能为空" }],
  role: [{ required: true, message: "角色不能为空" }]
})

/** 获取用户信息 */
const getUserInfo = async () => {
  const { data } = await ApiTree.user.detail(props.guid);
  if (data) {
    form.value = { ...data, checkPassword: "" };
  }
}
const initForm = () => {
  form.value = {
    guid: "",
    userName: "",
    realName: "",
    password: "",
    role: "",
    roleName: "",
    checkPassword: "",
  }
}
/**
 * 获取角色列表
 */
const roleList = ref<RoleVO[]>([]);
const getRoleList = async () => {
  const { data } = await ApiTree.role.getRole();
  if (data) {
    roleList.value = data;
  }
}
/**
 * 监听属性变化
 */
watch(() => props.guid, () => {
  if (props.guid) {
    // 获取用户详情
    getUserInfo()
    title.value = "编辑用户"
    formRules.password = []
    formRules.checkPassword = []
  } else {
    title.value = "添加用户"
    initForm()
    formRules.password = [{ required: true, validator: passwordValidator }];
    formRules.checkPassword = [{ required: true, validator: checkPasswordValidator }]
  }
}, { immediate: true })
watch(() => props.visible, () => {
  if (props.visible) {
    getRoleList();
  }
}, { immediate: true })
watch(() => form.value.realName, () => {
  if (!props.guid && form.value.realName) {
    getPy();
  }
}, { immediate: true })
const getPy = async () => {
  const { data } = await ApiTree.common.getPy(form.value.realName);
  if (data) {
    form.value.userName = data;
  }
}
/**提交表单 */
const onSubmit = () => {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      //
      form.value.roleName = roleList.value.find(x => x.code === form.value.role)?.name ?? "";
      if (props.guid) {
        const { success, msg } = await ApiTree.user.update(form.value);
        if (success) {
          ElMessage.success(msg);
        }
        emits("close", success);
      } else {
        const { success, msg } = await ApiTree.user.create(form.value);
        if (success) {
          ElMessage.success(msg);
        }
        emits("close", success);
      }
    }
  })
}
</script>
<style lang="scss" scope></style>
